package indi.zhifa.engine.starter.redis;

import indi.zhifa.engine.redis.utils.RedisTemplateProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@ConditionalOnProperty(prefix = "zhifa.redis",name = "enabled", havingValue = "true")
@Configuration
public class RedisCommonConfiguration {

    @Bean
    public RedisTemplateProvider redisTemplateProvider(@Qualifier("normal-redis-template") ObjectProvider<RedisTemplate<String, Object>> pNormalRedisTemplateProvider,
                                                       @Qualifier("cache-redis-template") ObjectProvider<RedisTemplate<String, Object>> pCacheRedisTemplateProvider) {
        return new RedisTemplateProvider(pNormalRedisTemplateProvider, pCacheRedisTemplateProvider);
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }


}
